<template>
  <div class="learning-container">
    <van-field
      v-model="selectValue"
      is-link
      readonly
      placeholder="请选择课程"
      @click="show = true"
    />
    <van-popup round v-model:show="show" position="bottom">
      <!-- 这里的级联选择器为了能够实现不仅仅选中叶子节点，而且也可以选中父节点，所以这个选择器只能设置为两级 -->
      <van-cascader
        title="请选择课程"
        :options="table"
        @close="show = false"
        @finish="onFinish"
      ></van-cascader>
    </van-popup>
    <!-- 自定义搜索框 -->
    <div class="custom-search-container">
      <div class="custom-search">
        <van-icon name="search" class="search-icon" @click="onSearch" />
        <input
          v-model="searchValue"
          type="text"
          class="search-input"
          placeholder="请输入搜索关键词"
          @keyup.enter="onSearch"
        />
        <van-icon
          v-if="searchValue"
          name="clear"
          class="clear-icon"
          @click="clearSearch"
        />
      </div>
    </div>

    <!-- 八宫格改为每行4个 -->
    <van-grid :column-num="4" :border="true" :gutter="8">
      <van-grid-item
        v-for="(item, index) in gridItems"
        :key="index"
        @click="handleClick(index)"
      >
        <template #icon>
          <img
            style="height: 40px; width: 40px"
            :src="item.icon"
            class="grid-icon"
          />
        </template>
        <template #text>
          <span class="grid-text">{{ item.text }}</span>
        </template>
      </van-grid-item>
    </van-grid>

    <!-- 问题列表区域 -->
    <div class="question-list-container">
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-list
          v-model:loading="loading"
          :finished="finished"
          :finished-text="finishedText"
          @load="onLoad"
          :immediate-check="true"
        >
          <van-cell
            v-for="(item, index) in tableData"
            :key="index"
            :title="item.question"
            is-link
            @click="showQuestionDetail(item)"
          />

          <!-- 自定义完成提示，当有数据时才显示 -->
          <template #finished>
            <div
              v-if="tableData && tableData.length > 0"
              class="list-finished-tip"
            >
              <van-icon name="warning-o" size="18" color="#909399" />
              <p>{{ finishedText }}</p>
            </div>
          </template>

          <!-- 空数据提示，统一处理搜索无结果和无题目的情况 -->
          <van-empty
            v-if="tableData && tableData.length === 0 && !loading && finished"
            :description="searchValue ? '未找到匹配题目' : '暂无题目数据'"
          >
            <template #default>
              <div class="empty-actions">
                <van-button
                  v-if="searchValue"
                  icon="close"
                  round
                  type="primary"
                  size="small"
                  @click="clearSearch"
                >
                  清除搜索
                </van-button>
                <van-button
                  icon="search"
                  round
                  type="primary"
                  size="small"
                  @click="onSelectCourse"
                >
                  选择其他课程
                </van-button>
              </div>
            </template>
          </van-empty>
        </van-list>
      </van-pull-refresh>
    </div>

    <!-- 问题详情弹出层 -->
    <van-popup
      v-model:show="questionDetailShow"
      round
      position="bottom"
      :style="{ maxHeight: '70%' }"
      closeable
    >
      <div class="question-detail">
        <h3 class="question-title">{{ currentQuestion?.question }}</h3>

        <div class="question-options">
          <div class="option-item" v-if="currentQuestion?.item1">
            <span class="option-content">{{ currentQuestion.item1 }}</span>
          </div>
          <div class="option-item" v-if="currentQuestion?.item2">
            <span class="option-content">{{ currentQuestion.item2 }}</span>
          </div>
          <div class="option-item" v-if="currentQuestion?.item3">
            <span class="option-content">{{ currentQuestion.item3 }}</span>
          </div>
          <div class="option-item" v-if="currentQuestion?.item4">
            <span class="option-content">{{ currentQuestion.item4 }}</span>
          </div>
          <div class="option-item" v-if="currentQuestion?.remark">
            <span class="option-content"
              ><span style="font-weight: bold">解析</span>：{{
                currentQuestion.remark
              }}</span
            >
          </div>
        </div>

        <div class="question-answer">
          <span class="answer-label">答案：</span>
          <span class="answer-content">{{ currentQuestion?.answer }}</span>
        </div>

        <van-button
          type="primary"
          block
          round
          class="close-btn"
          @click="questionDetailShow = false"
        >
          关闭
        </van-button>
      </div>
    </van-popup>

    <!-- 添加 Dialog 组件 -->
    <van-dialog
      v-model:show="dialogShow"
      title="自我测试"
      show-cancel-button
      @confirm="onConfirm"
      :before-close="(action) => (action === 'confirm' ? false : true)"
    >
      <div class="test-dialog-content">
        <van-field
          v-model="testCount"
          type="number"
          placeholder="请输入考试题目数量"
          :error="!!countError"
          :error-message="countError"
          @input="countError = ''"
        />
      </div>
    </van-dialog>
  </div>
</template>

<script setup>
import { getToken } from "@/utils/auth"; // get token from cookie
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import shouyeIcon from "@/assets/shouye.jpg";
import shunxuIcon from "@/assets/shunxu.jpg";
import suijiIcon from "@/assets/suiji.jpg";
import cuowuIcon from "@/assets/cuowu.jpg";
import shoucangIcon from "@/assets/shoucang.jpg";
import ceshiIcon from "@/assets/ceshi.jpg";
import huiguIcon from "@/assets/huigu.jpg";
import listenIcon from "@/assets/listen.jpg";
import subjectApi from "@/api/subject/index";
import lastRecord from "@/api/record/lastRecord";
import questionApi from "@/api/question/index";
import { useStore } from "vuex";
import seftTestApi from "@/api/selfTest/index";

const store = useStore();
const router = useRouter();
const searchValue = ref("");
const show = ref(false);
const selectValue = ref("");
const table = ref([]);
const tableData = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false);
const finishedText = ref("没有更多了");

const getSubject = async () => {
  const res = await subjectApi.getTree();
  table.value = res.data;
  table.value.forEach((item) => {
    if (item.children) {
      //在children数组的最前面增加一个数据
      item.children.unshift({
        text: item.text,
        value: item.value,
      });
    }
  });
};

const getLeafNodeIds = (nodes, targetId) => {
  const leafIds = [];

  const findLeafNodes = (node) => {
    if (!node.children || node.children.length === 0) {
      leafIds.push(node.value); // 假设节点的ID存储在value字段中
      return;
    }
    node.children.forEach((child) => findLeafNodes(child));
  };

  // 先找到目标节点
  const targetNode = findNodeByValue(nodes, targetId);
  if (targetNode) {
    findLeafNodes(targetNode);
  }

  return leafIds;
};

const findNodeByValue = (nodes, targetValue) => {
  for (const node of nodes) {
    if (node.value === targetValue) {
      return node;
    }
    if (node.children) {
      const found = findNodeByValue(node.children, targetValue);
      if (found) return found;
    }
  }
  return null;
};

const getQuestion = async (isRefresh = false) => {
  if (isRefresh) {
    currentPage.value = 1;
    tableData.value = [];
  }

  try {
    let leafNodeIds = getLeafNodeIds(table.value, store.getters.selectedId);
    const res = await questionApi.listBySubject(
      searchValue.value,
      leafNodeIds,
      currentPage.value,
      pageSize.value
    );

    if (isRefresh) {
      tableData.value = res.data;
    } else {
      // 如果是加载更多，则追加数据
      if (tableData.value) {
        tableData.value = [...tableData.value, ...res.data];
      } else {
        tableData.value = res.data;
      }
    }

    // 判断是否已加载完所有数据
    if (
      !res.data ||
      res.data.length < pageSize.value ||
      currentPage.value >= res.data.pages
    ) {
      finished.value = true;
    } else {
      finished.value = false;
    }
  } catch (error) {
    console.error("获取题目失败", error);
  } finally {
    loading.value = false;
    refreshing.value = false;
  }
};

// 下拉刷新
const onRefresh = async () => {
  finished.value = false;
  await getQuestion(true);
};

// 上拉加载更多
const onLoad = async () => {
  if (refreshing.value) return;

  // 如果是第一页且没有数据，不再请求
  if (
    currentPage.value === 1 &&
    tableData.value &&
    tableData.value &&
    tableData.value.length === 0
  ) {
    finished.value = true;
    loading.value = false;
    return;
  }

  // 加载下一页
  currentPage.value++;
  await getQuestion();
};

// 搜索触发
const onSearch = () => {
  // 这里执行您的搜索逻辑
  resetAndRefresh();
};

// 重置列表并刷新
const resetAndRefresh = async () => {
  // 重置列表状态
  currentPage.value = 1;
  finished.value = false;
  loading.value = false;
  tableData.value = [];

  // 显示刷新动画
  refreshing.value = true;

  // 获取新数据
  await getQuestion(true);

  // 重置刷新状态
  refreshing.value = false;
};

onMounted(async () => {
  if (getToken()) {
    selectValue.value = store.getters.selectValue;
    console.log(selectValue.value);

    await getSubject();
    await getQuestion(true);
  }
});

// 八宫格数据
const gridItems = [
  {
    text: "数据统计",
    icon: shouyeIcon, // 待添加图片路径
    path: "/learning/statistics",
  },
  {
    text: "顺序练习",
    icon: shunxuIcon, // 待添加图片路径
    path: "/learning/sequence",
  },
  {
    text: "随机练习",
    icon: suijiIcon, // 待添加图片路径
    path: "/learning/random",
  },
  {
    text: "错题练习",
    icon: cuowuIcon, // 待添加图片路径
    path: "/learning/wrong",
  },
  {
    text: "收藏练习",
    icon: shoucangIcon, // 待添加图片路径
    path: "/learning/favorite",
  },
  {
    text: "自我测试",
    icon: ceshiIcon, // 待添加图片路径
    path: "/learning/self-test",
  },
  {
    text: "回顾试卷",
    icon: huiguIcon, // 待添加图片路径
    path: "/learning/review",
  },
  {
    text: "听力练习",
    icon: listenIcon, // 待添加图片路径
    path: "/learning/listening",
  },
];

const handleClick = (index) => {
  // ... existing code ...

  // Check if course is selected before navigation
  if (!selectValue.value) {
    // Show course selection popup if no course selected
    show.value = true;
    return;
  }

  const text = gridItems[index].text;
  const id = store.getters.selectedId;
  switch (index) {
    case 0: // 数据统计
      router.push("/learning/statistics");
      break;
    case 1: // 顺序练习
      router.push({
        path: "/learning/learning",
        query: { type: text, selectedId: id },
      });
      break;

    case 2: // 随机练习
      router.push({
        path: "/learning/learning",
        query: { type: text, selectedId: id },
      });
      break;

    case 3: // 错题练习
      router.push({
        path: "/learning/learning",
        query: { type: text, selectedId: id },
      });
      break;
    case 4: // 收藏练习
      router.push({
        path: "/learning/learning",
        query: { type: text, selectedId: id },
      });
      break;

    case 5: // 自我测试
      // Show dialog for test question count
      showTestDialog();
      break;

    case 6: // 回顾试卷
      router.push({
        path: "/learning/review",
        query: { selectedId: id },
      });
      break;

    case 7: // 听力练习
      router.push("/learning/listening");
      break;
  }
};

// 添加一个 ref 来控制对话框显示
const dialogShow = ref(false);
// 添加一个 ref 来存储输入的数量
const testCount = ref("");
// 添加一个 ref 来存储输入错误提示
const countError = ref("");

// 更新 showTestDialog 函数
const showTestDialog = () => {
  dialogShow.value = true;
  testCount.value = ""; // 重置输入值
  countError.value = ""; // 重置错误提示
};

// 添加确认处理函数
const onConfirm = async () => {
  const count = parseInt(testCount.value);
  if (!testCount.value || isNaN(count) || count <= 0) {
    countError.value = "请输入大于0的数字";
    return;
  }

  if (!store.getters.selectedId) {
    countError.value = "请选择课程";
    return;
  }

  const res = await seftTestApi.batchInsert(store.getters.selectedId, count);
  router.push({
    path: "/learning/selfTest",
    query: {
      questionItemId: res.data,
      type: "selfTest",
    },
  });
  dialogShow.value = false;
};

// 选择完成时触发
const onFinish = async ({ selectedOptions }) => {
  let str = "";
  let selectedId;
  if (selectedOptions.length == 1) {
    selectedId = selectedOptions[0].value;
  } else {
    if (selectedOptions[1].value == selectedOptions[0].value) {
      selectedId = selectedOptions[0].value;
    } else {
      selectedId = selectedOptions[1].value;
    }
  }
  for (let i = 0; i < selectedOptions.length; i++) {
    str += selectedOptions[i].text + " ";
    if (i < selectedOptions.length - 1) {
      str += "/";
    }
  }
  selectValue.value = str;
  show.value = false;

  await lastRecord.addOrUpdate(selectedId, selectValue.value);
  //把选中的课程和课程ID存放到store中
  store.dispatch("learn/setSelectValue", selectValue.value);
  store.dispatch("learn/setSelectedId", selectedId);

  // 重置列表状态并刷新数据
  resetAndRefresh();
};

// 清除搜索
const clearSearch = () => {
  searchValue.value = "";
  onSearch();
};

// 点击"选择其他课程"按钮
const onSelectCourse = () => {
  show.value = true; // 打开课程选择弹窗
};

// 问题详情相关
const questionDetailShow = ref(false);
const currentQuestion = ref(null);

// 显示问题详情
const showQuestionDetail = (question) => {
  currentQuestion.value = question;
  questionDetailShow.value = true;
};
</script>

<style scoped>
.learning-container {
  padding: 12px; /* 减小边距 */
  background-color: #f7f8fa;
  min-height: 100vh;
}

.grid-icon {
  width: 48px;
  height: 48px;
  margin-bottom: 8px;
}

.grid-text {
  font-size: 12px; /* 减小文字大小 */
  color: #323233;
}

:deep(.van-grid-item__content) {
  padding: 8px 4px; /* 减小内边距 */
}

:deep(.van-search) {
  margin-bottom: 12px;
}

.question-list-container {
  margin-top: 15px;
  height: calc(100vh - 280px);
  overflow-y: auto;
}

:deep(.van-cell__title) {
  white-space: normal;
  word-break: break-word;
}

.list-finished-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
}

.list-finished-tip p {
  margin-left: 10px;
  font-size: 14px;
  color: #909399;
}

.empty-actions {
  display: flex;
  gap: 8px;
  justify-content: center;
  margin-top: 8px;
}

:deep(.van-empty__description) {
  margin-bottom: 8px;
  color: #909399;
}

.question-detail {
  padding: 20px 16px;
}

.question-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 16px;
  line-height: 1.4;
}

.question-options {
  margin-bottom: 20px;
}

.option-item {
  margin-bottom: 12px;
  display: flex;
}

.option-label,
.answer-label {
  color: #666;
  font-weight: 500;
  flex-shrink: 0;
  width: 60px;
}

.option-content,
.answer-content {
  flex: 1;
}

.question-answer {
  margin-bottom: 20px;
  padding-top: 10px;
  border-top: 1px solid #ebedf0;
  display: flex;
}

.answer-content {
  color: #f44336;
  font-weight: bold;
}

.close-btn {
  margin-top: 10px;
}

:deep(.van-cell) {
  line-height: 1.5;
  padding: 12px 16px;
}

:deep(.van-cell__title) {
  flex: 3;
}

.custom-search-container {
  padding: 10px 12px;
  background-color: #ffffff;
  margin-bottom: 12px;
}

.custom-search {
  display: flex;
  align-items: center;
  height: 34px;
  padding: 0 10px;
  background-color: #f7f8fa;
  border-radius: 17px;
  position: relative;
}

.search-icon {
  font-size: 16px;
  color: #969799;
  margin-right: 6px;
  flex-shrink: 0;
}

.search-input {
  flex: 1;
  height: 100%;
  border: none;
  outline: none;
  background: transparent;
  font-size: 14px;
  color: #323233;
  padding: 0;
  margin: 0;
  line-height: 34px; /* 与容器高度一致，实现垂直居中 */
}

.search-input::placeholder {
  color: #969799;
}

.clear-icon {
  font-size: 16px;
  color: #c8c9cc;
  padding: 4px;
  margin-left: 4px;
  flex-shrink: 0;
  cursor: pointer;
}

.clear-icon:active {
  opacity: 0.6;
}

.test-dialog-content {
  padding: 20px 16px;
}
</style>
